//file_for_patch.c
// patch demo file tool
//
/*
 This is the HDiffPatch copyright.

 Copyright (c) 2012-2019 HouSisong All Rights Reserved.

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
#include "file_for_patch.h"
#include "sys.h"
 /*
 #ifdef _MSC_VER
 #   include <io.h>    //_chsize_s
 #endif
 */
static unsigned int oldcnt = 0;

//hpatch_BOOL _hpatch_getPathStat_noEndDirSeparator(const char* path_utf8, hpatch_TPathType* out_type,
//    hpatch_StreamPos_t* out_fileSize, size_t* out_st_mode) {

//}

#if defined(ANDROID) && (__ANDROID_API__ < 24)
static off64_t _import_lseek64(hpatch_FileHandle file, hpatch_StreamPos_t seekPos, int whence) {
    int fd;
    if (feof(file))
        rewind(file);
    setbuf(file, NULL);
    fd = fileno(file);
    if (fd < 0) return -1;
    return lseek64(fd, seekPos, whence);
}
#endif

hpatch_inline static
hpatch_BOOL _import_fileSeek64(hpatch_FileHandle file, hpatch_StreamPos_t seekPos) {
    oldcnt = seekPos;
    return 1;
}

hpatch_inline static
hpatch_BOOL _import_fileClose(hpatch_FileHandle* pfile) {
    hpatch_FileHandle file = *pfile;
    if (file) {
        *pfile = 0;
        if (0 != fclose(file))
            return hpatch_FALSE;
    }
    return hpatch_TRUE;
}

hpatch_BOOL _import_fileRead(hpatch_FileHandle file, TByte* buf, TByte* buf_end) {
    while (buf < buf_end) {
        size_t readLen = (size_t)(buf_end - buf);
        if (readLen > hpatch_kFileIOBestMaxSize) readLen = hpatch_kFileIOBestMaxSize;    
        for (int i = 0; i < readLen; i++)
        {
            buf[i] = old[oldcnt++];
        }

        buf += readLen;
    }
    return buf == buf_end;
}

#if (_IS_USED_WIN32_UTF8_WAPI)
#   define _kFileReadMode  L"rb"
#   define _kFileWriteMode L"wb+"
#   define _kFileReadWriteMode L"rb+"
#else
#   define _kFileReadMode  "rb"
#   define _kFileWriteMode "wb+"
#   define _kFileReadWriteMode "rb+"
#endif

#if (_IS_USED_WIN32_UTF8_WAPI)
static hpatch_FileHandle _import_fileOpenByMode(const char* fileName_utf8, const wchar_t* mode_w) {
    wchar_t fileName_w[hpatch_kPathMaxSize];
    int wsize = _utf8FileName_to_w(fileName_utf8, fileName_w, hpatch_kPathMaxSize);
    if (wsize > 0) {
# if (_MSC_VER>=1400) // VC2005
        hpatch_FileHandle file = 0;
        int err = _wfopen_s(&file, fileName_w, mode_w);
        return (err == 0) ? file : 0;
# else
        return _wfopen(fileName_w, mode_w);
# endif
    }
    else {
        return 0;
    }
}
#else
hpatch_inline static
hpatch_FileHandle _import_fileOpenByMode(const char* fileName_utf8, const char* mode) {
    return fopen(fileName_utf8, mode);
}
#endif

hpatch_BOOL _import_fileOpenRead(const char* fileName_utf8, hpatch_FileHandle* out_fileHandle,
    hpatch_StreamPos_t* out_fileLength) {
    return hpatch_TRUE;
}

hpatch_BOOL _import_fileOpenCreateOrReWrite(const char* fileName_utf8, hpatch_FileHandle* out_fileHandle) {
    hpatch_FileHandle file = 0;
    assert(out_fileHandle != 0);
    if (out_fileHandle == 0) { _setFileErrNo(EINVAL); return hpatch_FALSE; }
    file = _import_fileOpenByMode(fileName_utf8, _kFileWriteMode);
    if (file == 0) return hpatch_FALSE;
    *out_fileHandle = file;
    return hpatch_TRUE;
}

hpatch_BOOL _import_fileReopenWrite(const char* fileName_utf8, hpatch_FileHandle* out_fileHandle,
    hpatch_StreamPos_t* out_curFileWritePos) {

    return hpatch_TRUE;
}


#define _ferr_return()          { _update_ferr(self->fileError);   return hpatch_FALSE; }
#define _ferr_returnv(v)        { _update_ferrv(self->fileError,v); return hpatch_FALSE; }
#define _rw_ferr_return()       { self->m_fpos=~(hpatch_StreamPos_t)0; _ferr_return(); }
#define _rw_ferr_returnv(v)     { self->m_fpos=~(hpatch_StreamPos_t)0; _ferr_returnv(v); }

static hpatch_BOOL _TFileStreamInput_read_file(const hpatch_TStreamInput* stream, hpatch_StreamPos_t readFromPos,
    TByte* out_data, TByte* out_data_end) {
    size_t readLen;
    hpatch_TFileStreamInput* self = (hpatch_TFileStreamInput*)stream->streamImport;
    assert(out_data <= out_data_end);
    readLen = (size_t)(out_data_end - out_data);
    if (readLen == 0) return hpatch_TRUE;
    //if ((readLen > self->base.streamSize)
    //    || (readFromPos > self->base.streamSize - readLen)) _ferr_returnv(EFBIG);
    if (self->m_fpos != readFromPos + self->m_offset) {
        if (!_import_fileSeek64(self->m_file, readFromPos + self->m_offset)) _rw_ferr_return();
    }
    if (!_import_fileRead(self->m_file, out_data, out_data + readLen)) _rw_ferr_return();
    self->m_fpos = readFromPos + self->m_offset + readLen;
    return hpatch_TRUE;
}

hpatch_BOOL hpatch_TFileStreamInput_open(hpatch_TFileStreamInput* self, const char* fileName_utf8) {
    assert(self->m_file == 0);
    self->fileError = hpatch_FALSE;
    if (self->m_file) _ferr_returnv(EINVAL);
    //if (!_import_fileOpenRead(fileName_utf8, &self->m_file, &self->base.streamSize))
    //    _ferr_return();
    //self->m_file = "";
    self->base.streamSize = sizeold;
    self->base.streamImport = self;
    self->base.read = _TFileStreamInput_read_file;
    self->m_fpos = 0;
    self->m_offset = 0;
    return hpatch_TRUE;
}

hpatch_BOOL hpatch_TFileStreamInput_close(hpatch_TFileStreamInput* self) {
    if (!_import_fileClose(&self->m_file)) _ferr_return();
    return hpatch_TRUE;
}

hpatch_BOOL hpatch_TFileStreamOutput_open(hpatch_TFileStreamOutput* self, const char* fileName_utf8,
    hpatch_StreamPos_t max_file_length) {
    assert(self->m_file == 0);
    self->fileError = hpatch_FALSE;
    if (self->m_file) _ferr_returnv(EINVAL);
    //if (!_import_fileOpenCreateOrReWrite(fileName_utf8, &self->m_file))
    //    _ferr_return();
    //self->m_file = "";
    self->base.streamImport = self;
    self->base.streamSize = max_file_length;
    //self->base.read_writed = _hpatch_TFileStreamOutput_read_file;
    //self->base.write = "";
    self->m_fpos = 0;
    self->m_offset = 0;
    self->is_in_readModel = hpatch_FALSE;
    self->is_random_out = hpatch_FALSE;
    self->out_length = 0;
    return hpatch_TRUE;
}
